// pages/index/detailsC/index.js
import Dialog from '../../../../miniprogram_npm/@vant/weapp/dialog/dialog';
import Toast from '../../../../miniprogram_npm/@vant/weapp/toast/toast';
import { IMOU_APPID, IMOU_APPSECRET } from '../../../../utils/storage';
const $api = require('../../../../request/api').API;
const app = getApp();
Page({
  data: {
    id: '',
    // 住户id
    houseId: '',
    // 呼叫器id
    beeperId: '',
    // 设备id
    equipId: '',
    equipMac: '',
    //--------------------------------------------------------------
    linkName: '',
    phone: '',
    address: '',
    provinceName: '',
    cityName: '',
    areaName: '',
    streetName: '',
    villageName: '',
    callingName: '',
    callingStatus: 0,
    callingErrorStatus: 0,
    equipNickName: '',
    installArea: '',
    equipCode: '',
    money: 0,
    activeDate: '',
    // 标签列表
    tagList: [
      {
        beeperTagId: '1',
        tagName: '帅气'
      }
    ],
    createDate: '',
    //-----------------------------------------------------------------
    // 设置wifi弹框
    // 设置新增标签弹框
    showTagOverlay: false,
    // 点击标签分类显示
    selectClassShow: false,
    selectClassName: '点击选择分类',
    selectClassId: '',
    tagClass: [],
    // 是否为主用户
    mainFlag: 0,
    // 修改昵称或者安装区域弹框
    showUpdateData: false,
    showType: 1, //1代表昵称修改 2代表安装区域修改
    tempData: '' //临时数据，用来修改昵称和安装区域
  },

  onLoad(options) {
    let id = options.beeperId;
    if (id != undefined) {
      this.setData({
        id: id
      });
    }
  },

  // 请求数据
  getData(id) {
    let params = {
      id: this.data.id
    };
    $api
      .getBeeperC(params)
      .then(res => {
        if (res.data.status == 0) {
          var data = res.data.data;
          this.setData({
            activeDate: data.activeDate,
            houseId: data.houseId,
            beeperId: data.beeperId,
            createDate: data.createDate,
            equipId: data.equipId,
            wifiName: data.wifiName,
            wifiPwd: data.wifiPwd,
            linkName: data.linkName,
            phone: data.phone,
            address: data.address == '待补充' ? '' : data.address,
            provinceName: data.provinceName,
            cityName: data.cityName,
            areaName: data.areaName,
            streetName: data.streetName,
            villageName: data.villageName,
            callingName: data.equipName,
            callingStatus: data.equipState,
            callingErrorStatus: data.errorState,
            money: data.balance,
            tagList: data.tags,
            mainFlag: data.mainFlag,
            equipNickName: data.equipNickName,
            installArea: data.installArea,
            equipCode: data.equipCode,
            equipMac: data.equipMac
          });
        }
      })
      .catch(err => {
        console.log(err);
      });
  },
  onShow() {
    this.getData(this.data.id);
  },
  onSelectClass(event) {
    this.setData({
      selectClassName: event.detail.name,
      selectClassId: event.detail.id
    });
  },
  // 解绑设备
  jiebang() {
    Dialog.confirm({
      title: '提示',
      message: '确认解绑当前设备吗？'
    })
      .then(() => {
        let params = {
          id: this.data.equipId
        };
        $api
          .unbindBinding(params)
          .then(res => {
            console.log('解绑设备', res);
            if (res.data.status == 0) {
              wx.showToast({
                title: '解绑成功！'
              });
              setTimeout(() => {
                wx.switchTab({
                  url: '/pages/equipment/index'
                });
              }, 1000);
            }
          })
          .catch(err => {
            console.log('解绑设备', err);
          });
      })
      .catch(() => {});
  },
  phoneInput(e) {
    let value = e.detail.value;
    this.setData({
      phone: value
    });
  },
  addressInput(e) {
    let value = e.detail.value;
    this.setData({
      address: value
    });
  },
  tagNameInput(e) {
    let value = e.detail.value;
    this.setData({
      addTagName: value
    });
  },
  // 打开修改昵称弹框
  openUpdateData(e) {
    let type = e.currentTarget.dataset.type;
    this.setData({
      showUpdateData: true,
      showType: type,
      tempData: type == 1 ? this.data.equipNickName : this.data.installArea
    });
  },
  // 关闭修改昵称弹框
  closeUpdateData() {
    this.setData({
      showUpdateData: false
    });
  },
  // 输入绑定
  dataInput(e) {
    let value = e.detail.value;
    this.setData({
      tempData: value
    });
  },
  // 修改昵称
  UpdateData() {
    if (!this.data.tempData && this.data.showType == 1) {
      Toast('请输入昵称');
      return;
    } else if (!this.data.tempData && this.data.showType == 2) {
      Toast('请输入安装区域');
      return;
    }
    let params = {
      id: this.data.equipId,
      name: this.data.tempData,
      state: this.data.showType
    };
    $api
      .UpdataName(params)
      .then(res => {
        if (res.data.status == 0) {
          if (this.data.showType == 1) {
            wx.showToast({
              title: '设置昵称成功'
            });
          } else {
            wx.showToast({
              title: '设置成功'
            });
          }

          this.setData({
            showUpdateData: false
          });
          this.getData(this.data.id);
        }
      })
      .catch(err => {
        console.log(err);
      });
  },
  /**
   * 前往通道列表
   */
  async handleGotoCameraList() {
    const { equipMac } = this.data;
    const params = {
      appId: IMOU_APPID,
      appSecret: IMOU_APPSECRET
    };
    Toast.loading('数据加载中');
    const { result } = await $api.getImouToken(params);
    if (!result) {
      Toast.fail('获取设备token失败');
      Toast.clear();
      return;
    }
    app.globalData.IMOU_TOKEN = result.data.accessToken;
    Toast.clear();
    const channelListResult = await $api.listDeviceDetailsByIds({
      deviceList: [{ deviceId: this.data.equipMac }],
      token: result.data.accessToken
    });
    const deviceInfo = (channelListResult.result.data?.deviceList || [])[0];
    if (!deviceInfo) {
      Toast.fail('没有找到该设备的监控视频流');
      return;
    }
    const channelList = deviceInfo.channelList || [];
    channelList.forEach(item => {
      const { lastOffLineTime } = item;
      const year = lastOffLineTime.slice(0, 4);
      const month = lastOffLineTime.slice(4, 6);
      const day = lastOffLineTime.slice(6, 8);
      const hours = lastOffLineTime.slice(9, 11);
      const minutes = lastOffLineTime.slice(11, 13);
      const seconds = lastOffLineTime.slice(13, 15);
      item.lastOffLineTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    });
    console.log(channelList);
    if (channelList.length === 0) {
      Toast.fail('该设备没有视频通道');
      return;
    }
    if (channelList.length === 1) {
      wx.navigateTo({
        url: `../camera/index?deviceinfo=${equipMac}_${channelList[0].channelId}_${channelList[0].channelAbility}_${channelList[0].channelStatus}_${channelList[0].catalog}`
      });
    } else {
      wx.navigateTo({
        url: '../cameraChannelList/index?deviceId=' + equipMac
      });
    }
  }
});
